#!/bin/bash

# 腾讯云COSCLI自动安装脚本
# 基于官方文档: https://cloud.tencent.com/document/product/436/63144

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检测操作系统
detect_os() {
    case "$(uname -s)" in
        Darwin*) echo "macos" ;;
        Linux*) echo "linux" ;;
        CYGWIN*|MINGW*|MSYS*) echo "windows" ;;
        *) echo "unknown" ;;
    esac
}

# 检测架构
detect_arch() {
    case "$(uname -m)" in
        x86_64|amd64) echo "amd64" ;;
        arm64|aarch64) echo "arm64" ;;
        *) echo "unknown" ;;
    esac
}

# 检查COSCLI是否已安装
check_coscli() {
    if command -v coscli >/dev/null 2>&1; then
        local version=$(coscli --version 2>/dev/null | head -n1 || echo "unknown")
        log_info "COSCLI已安装，版本: $version"
        return 0
    else
        log_warn "COSCLI未安装"
        return 1
    fi
}

# 安装COSCLI
install_coscli() {
    local os=$(detect_os)
    local arch=$(detect_arch)
    local coscli_dir="$HOME/.coscli"
    local coscli_bin="$coscli_dir/coscli"

    log_step "开始安装COSCLI..."
    log_info "操作系统: $os"
    log_info "架构: $arch"

    # 创建安装目录
    mkdir -p "$coscli_dir"

    # 确定下载URL
    local download_url=""
    local file_name=""

    case "$os" in
        "macos")
            if [ "$arch" = "arm64" ]; then
                file_name="coscli-darwin-arm64"
            else
                file_name="coscli-darwin-amd64"
            fi
            ;;
        "linux")
            if [ "$arch" = "arm64" ]; then
                file_name="coscli-linux-arm64"
            elif [ "$arch" = "arm" ]; then
                file_name="coscli-linux-arm"
            elif [ "$arch" = "386" ]; then
                file_name="coscli-linux-386"
            else
                file_name="coscli-linux-amd64"
            fi
            ;;
        *)
            log_error "不支持的操作系统: $os"
            exit 1
            ;;
    esac

    # 优先使用国内下载源
    download_url="https://cosbrowser.cloud.tencent.com/software/coscli/$file_name"
    local backup_url="https://github.com/tencentyun/coscli/releases/latest/download/$file_name"

    log_info "下载地址: $download_url"
    log_info "文件名: $file_name"

    # 下载文件
    if ! curl -fsSL "$download_url" -o "$coscli_bin"; then
        log_warn "国内源下载失败，尝试GitHub源..."
        if ! curl -fsSL "$backup_url" -o "$coscli_bin"; then
            log_error "下载失败，请手动下载:"
            log_error "1. 访问: https://cosbrowser.cloud.tencent.com/software/coscli"
            log_error "2. 下载: $file_name"
            log_error "3. 移动到: $coscli_bin"
            exit 1
        fi
    fi

    # 设置执行权限
    chmod +x "$coscli_bin"

    # 创建符号链接到PATH
    local link_path="/usr/local/bin/coscli"
    if [ -w "/usr/local/bin" ]; then
        ln -sf "$coscli_bin" "$link_path"
        log_info "已创建符号链接: $link_path"
    else
        # 如果没有权限，添加到PATH
        local shell_rc=""
        case "$SHELL" in
            */bash) shell_rc="$HOME/.bashrc" ;;
            */zsh) shell_rc="$HOME/.zshrc" ;;
            *) shell_rc="$HOME/.profile" ;;
        esac

        if ! grep -q "$coscli_dir" "$shell_rc" 2>/dev/null; then
            echo "" >> "$shell_rc"
            echo "# 腾讯云COSCLI" >> "$shell_rc"
            echo "export PATH=\"\$PATH:$coscli_dir\"" >> "$shell_rc"
            log_info "已添加到 $shell_rc，请重新加载shell或运行: source $shell_rc"
        fi
    fi

    log_info "✅ COSCLI安装完成!"
}

# 配置COSCLI
configure_coscli() {
    log_step "配置COSCLI..."

    # 加载环境变量
    if [ -f ".env" ]; then
        log_info "加载 .env 文件..."
        set -a
        source .env
        set +a
    fi

    # 检查必要的环境变量
    if [ -z "$TENCENT_SECRET_ID" ] || [ -z "$TENCENT_SECRET_KEY" ]; then
        log_error "缺少腾讯云访问密钥"
        log_info "请设置环境变量或创建 .env 文件:"
        echo "TENCENT_SECRET_ID='你的SecretID'"
        echo "TENCENT_SECRET_KEY='你的SecretKey'"
        exit 1
    fi

    # 创建配置目录
    mkdir -p "$HOME/.cos"

    # 生成配置文件
    cat > "$HOME/.cos.yaml" << EOF
# 腾讯云COSCLI配置文件
# 自动生成于 $(date)

# 默认配置段
cos:
  base:
    secretid: ${TENCENT_SECRET_ID}
    secretkey: ${TENCENT_SECRET_KEY}
    sessiontoken: ""  # 临时密钥时填写
    protocol: https
    region: ${TENCENT_REGION:-ap-guangzhou}

# 默认存储桶配置
  default:
    bucket: ${TENCENT_BUCKET:-claude-code-mirror}
    region: ${TENCENT_REGION:-ap-guangzhou}

# 日志配置
log:
  level: info
  file: /tmp/coscli.log

# 并发配置
concurrent:
  # 上传分块并发数
  multipart:
    upload:
      threads: 5
    copy:
      threads: 5
EOF

    log_info "✅ 配置文件已创建: $HOME/.cos.yaml"
    log_info "配置的存储桶: ${TENCENT_BUCKET:-claude-code-mirror}"
    log_info "配置的区域: ${TENCENT_REGION:-ap-guangzhou}"
}

# 测试COSCLI连接
test_coscli() {
    log_step "测试COSCLI连接..."

    # 列出存储桶来测试连接
    if coscli ls cos://${TENCENT_BUCKET:-claude-code-mirror} --region ${TENCENT_REGION:-ap-guangzhou} >/dev/null 2>&1; then
        log_info "✅ COSCLI连接测试成功"
        return 0
    else
        log_warn "连接测试失败，但配置可能仍然有效"
        log_warn "可能是存储桶不存在或权限问题"
        return 1
    fi
}

# 显示使用说明
show_usage() {
    echo ""
    echo "🎉 COSCLI安装完成！"
    echo ""
    echo "常用命令:"
    echo "  coscli ls cos://bucket-name/           # 列出文件"
    echo "  coscli upload local-file cos://bucket/  # 上传文件"
    echo "  coscli download cos://bucket/file ./   # 下载文件"
    echo "  coscli sync local-dir cos://bucket/    # 同步目录"
    echo ""
    echo "配置文件位置: $HOME/.cos.yaml"
    echo "日志文件位置: /tmp/coscli.log"
    echo ""
    echo "下一步:"
    echo "1. 运行: ./upload-to-cdn.sh --tencent"
    echo "2. 或手动上传: coscli sync ./claude-mirror cos://your-bucket/claude-mirror"
}

# 主函数
main() {
    echo "======================================"
    echo "  腾讯云COSCLI自动安装脚本"
    echo "  基于官方文档 v1.0"
    echo "======================================"
    echo ""

    # 检查依赖
    if ! command -v curl >/dev/null 2>&1; then
        log_error "需要安装 curl"
        exit 1
    fi

    # 检查是否已安装
    if check_coscli; then
        read -p "COSCLI已安装，是否重新配置? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            configure_coscli
            test_coscli
            show_usage
            exit 0
        fi
    fi

    # 安装COSCLI
    install_coscli

    # 配置COSCLI
    configure_coscli

    # 测试连接
    test_coscli

    # 显示使用说明
    show_usage
}

# 运行主函数
main "$@"